package edu.xhu;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.TeachingBean;
import com.constant.Constant;
import com.data.TeachingListData;
import com.net.ClientError;
import com.net.LoadData;
import com.net.RequestListener;
import com.net.RequestParameter;

import edu.xhu.adapters.EduTeaNameListAdapter;
import edu.xhu.util.DatabaseAdapter;
import edu.xhu.view.LoadingDialog;

/**
 * 学生名单
 * @author swerit
 *
 */
public class EduTeaNameList extends Activity{

	private Button mBtnBack, mBtnQuery, mBtnRefresh;
	private TextView title;
	private EduTeaNameListAdapter adapter;
	private ArrayList<TeachingBean> mTeachList;						//一门课的学生列表
	private XhuApplication application;
	private ListView nameListView;
	private ArrayList<String> classes;								//科目和下一次发送请求数据的列表，后台返回，未解析
	private int currentIndex = 0;									//当前界面显示的科目指针
	
	private Spinner spinner;
	
	private ArrayList<String> classesName, requetStrings;			//科目列表，下一次发送请求的数据列表
	
	//记录第一请求名单时返回的一些数据，后面几次请求需要
	private String sViewState,
				   sXn,
				   sXq,
				   sEventTarget,
				   sEventArgument,
				   sKcmc,
				   sBj;
	
	//添加备注信息界面控件
	private LayoutInflater mInflater;
	private Dialog customDialog;
	private View popView;
	private TextView mStuTitleName;
	private Button mBtnCancel, mBtnConfirm;
	private EditText mRemarkEditText;
	
	private DatabaseAdapter dbAdapter;
	
	//表示当前是从网络加载数据还是从本地数据库加载数据.true-网络加载,false-本地加载
	private boolean isLocal = false;
	//请求网络的参数是否已经加载到本地，true-已经加载到本地，false-没有加载到本地
	private boolean hasParam = false;
	
	private int mCurrentModifyStudentIndex;				//当前正在添加备注信息的学生的指针
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edu_namelist);
		
		initView();
		setListener();
		loadData();
	}
	
	private void initView(){
		application				= (XhuApplication) getApplication();
		nameListView			= (ListView) findViewById(R.id.listview_namelist);
		mBtnBack				= (Button) findViewById(R.id.button_back);
		title					= (TextView) findViewById(R.id.title);
		spinner					= (Spinner) findViewById(R.id.spinner_classes);
		mBtnQuery				= (Button) findViewById(R.id.button_query);
		mBtnRefresh				= (Button) findViewById(R.id.button_refresh);
		mInflater				= LayoutInflater.from(this);
		classesName				= new ArrayList<String>();
		requetStrings			= new ArrayList<String>();
		customDialog 			= new Dialog(this);
		
		popView					= mInflater.inflate(R.layout.edu_namelist_remark, null);
		customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);  
		customDialog.setContentView(popView);
		mBtnCancel				= (Button) popView.findViewById(R.id.button_cancel);
		mBtnConfirm				= (Button) popView.findViewById(R.id.button_yes);
		mRemarkEditText			= (EditText) popView.findViewById(R.id.edittext_namelist_remark);
		mStuTitleName			= (TextView) popView.findViewById(R.id.textview_stu_name);
		
		dbAdapter = new DatabaseAdapter(EduTeaNameList.this);
	}
	
	private void setListener(){
		mBtnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				currentIndex = arg2;
			}
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		
		//本地查询按钮点击事件
		mBtnQuery.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (classesName.size() == 0){
					Toast.makeText(EduTeaNameList.this, "没有本地数据，请联网加载数据！", Toast.LENGTH_LONG).show();
					return;
				}
				
				queryLocalData(classesName.get(currentIndex));
			}
		});
		
		mBtnRefresh.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showRefreshDialog();
			}
		});
		
		nameListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				mCurrentModifyStudentIndex = arg2;
				customDialog.show();
				TeachingBean bean = mTeachList.get(arg2);
				mStuTitleName.setText(bean.name);
				mRemarkEditText.setText(bean.remark);
			}
		});
		
		mBtnCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				customDialog.dismiss();
			}
		});
		
		mBtnConfirm.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				/**
				 * 将数据保存在数据库中，并且刷新界面
				 */
				String remark = mRemarkEditText.getText().toString().trim();
				
				dbAdapter.openDatabase();
				dbAdapter.saveRemark(mTeachList.get(mCurrentModifyStudentIndex).name
						, classesName.get(currentIndex), remark);
				dbAdapter.closeDatabase();
				
				mTeachList.get(mCurrentModifyStudentIndex).remark = remark;
				adapter.notifyDataSetChanged();
				
				customDialog.dismiss();
			}
		});
	}
	
	/**
	 * 加载数据：1-首先从数据库中加载；2-数据库中没有则从网络加载
	 */
	private void loadData(){
		dbAdapter.openDatabase();
		
		classesName = dbAdapter.getCourseNameList();
		
		if (classesName.size() == 0){
			//第一次进入该界面，本地没有数据，从网络加载
			if (!application.isLogin()){
				Toast.makeText(EduTeaNameList.this, "没有本地数据，请联网加载数据！", Toast.LENGTH_LONG).show();
				dbAdapter.closeDatabase();
				return;
			}
			
			isLocal = false;
			loadDataFirstFromWeb();
			
		}else {
			//继续加载本地数据
			//默认显示第一个科目的数据
			isLocal = true;
			currentIndex = 0;
			initSpinner();
//			Log.e("加载的科目是：", classesName.get(currentIndex));
			
			if (null != dbAdapter.getOneCourseStudents(classesName.get(currentIndex))){
				mTeachList = dbAdapter.getOneCourseStudents(classesName.get(currentIndex));
				refreshFrame();
			}
		}
		
		dbAdapter.closeDatabase();
	}
	
	
	/**
	 * 第一次从网络加载数据
	 */
	private void loadDataFirstFromWeb(){
		mBtnBack.post(new Runnable() {
			public void run() {
				LoadingDialog.showWindow(EduTeaNameList.this);
			}
		});
		
		String name = application.getUserName().split("老师")[0];
		String utf8Name = null;
		try {
			utf8Name = URLEncoder.encode(name, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		RequestParameter parameter =new RequestParameter();
		parameter.add("url", application.getTeaNameListUrl().replaceAll(name, utf8Name));
		parameter.add("referer", application.getRefererUrl());
		
		LoadData.loadData(Constant.TEACHING_LIST_DATA, parameter, new RequestListener() {
			public void onError(ClientError ed) {
				LoadingDialog.dismiss();
				ErrorShow.showError(EduTeaNameList.this, ed);
			}
			
			public void onComplete(Object obj) {
				TeachingListData data = (TeachingListData) obj;
				
//				data.printData();
				
				if (null == data.getTeachList()){
					LoadingDialog.dismiss();
					Toast.makeText(EduTeaNameList.this, "没有数据", 0).show();
					return;
				}
				mTeachList = data.getTeachList();
				
				//获取下一次请求需要的参数
				sViewState 		 = data.getViewState();
				sXn		  		 = data.getXn();
				sXq		  		 = data.getXq();
				sEventTarget 	 = data.getEventTarget();
				sEventArgument   = data.getEventArgument();
				classes			 = data.getClassList();
				sBj				 = data.getBj();
				currentIndex	 = data.getSelectedClass();
				
				Iterator<String> iterator = classes.iterator();
				while(iterator.hasNext()){
					String s = iterator.next();
					String reString[] = s.split("\\|");		//对于“|”和“.”这样的转意字符需要这样处理来分隔
					classesName.add(reString[0].trim());
					requetStrings.add(reString[1].trim());
				}
				sKcmc			 = requetStrings.get(currentIndex);
				
				hasParam = true;			//设置获得请求参数的标志为true
				initSpinner();
				refreshFrame();
				//将数据保存在本地数据库中
				saveDataLocal(classesName.get(currentIndex));
				
				LoadingDialog.dismiss();
			}
		});
	}
	
	/**
	 * 从网络加载数据，第一次加载之后使用该接口
	 * 其中只需要将kcmc参数改变即可实现加载不同科目的学生信息
	 */
	private void loadDataNextFromWeb(){
		mBtnBack.post(new Runnable() {
			public void run() {
				LoadingDialog.showWindow(EduTeaNameList.this);
			}
		});
		
		String name = application.getUserName().split("老师")[0];
		String utf8Name = null;
		try {
			utf8Name = URLEncoder.encode(name, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		RequestParameter parameter =new RequestParameter();
		parameter.add("url", application.getTeaNameListUrl().replaceAll(name, utf8Name));
		parameter.add("referer", application.getRefererUrl());
		parameter.add("__EVENTTARGET", sEventTarget);
		parameter.add("__EVENTARGUMENT", sEventArgument);
		parameter.add("__VIEWSTATE", sViewState);
		parameter.add("xn", sXn);
		parameter.add("xq", sXq);
		parameter.add("kcmc", sKcmc);					//该参数控制请求的科目不同
		parameter.add("rdBtnSort", "按学号排序");
		parameter.add("bj", sBj);
		
		LoadData.loadData(Constant.TEACHING_LIST_DATA, parameter, new RequestListener() {
			public void onError(ClientError ed) {
				LoadingDialog.dismiss();
				ErrorShow.showError(EduTeaNameList.this, ed);
			}
			
			public void onComplete(Object obj) {
				TeachingListData data = (TeachingListData) obj;
				
//				data.printData();
				
				if (null == data.getTeachList()){
					LoadingDialog.dismiss();
					Toast.makeText(EduTeaNameList.this, "没有数据", 0).show();
					return;
				}
				
				mTeachList = data.getTeachList();
				refreshFrame();
				
				saveDataLocal(classesName.get(currentIndex));
				
				LoadingDialog.dismiss();
			}
		});
	}
	
	/**
	 * 获取后面几次请求网络的请求参数信息，请求完参数之后判断返回的课表信息是否和需要的课表数据一样，
	 * 如果一样则保存并且刷新界面，如果不是则根据课程名字从网络加载数据
	 */
	private void getParamenter(final String courseName){
//		Log.e("getParamenter请求的科目是", courseName);
		
		mBtnBack.post(new Runnable() {
			public void run() {
				LoadingDialog.showWindow(EduTeaNameList.this);
			}
		});
		
		RequestParameter parameter =new RequestParameter();
		String name = application.getUserName().split("老师")[0];
		String utf8Name = null;
		try {
			utf8Name = URLEncoder.encode(name, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		parameter.add("url", application.getTeaNameListUrl().replaceAll(name, utf8Name));
		parameter.add("referer", application.getRefererUrl());
		
		LoadData.loadData(Constant.TEACHING_LIST_DATA, parameter, new RequestListener() {
			public void onError(ClientError ed) {
				LoadingDialog.dismiss();
				ErrorShow.showError(EduTeaNameList.this, ed);
			}
			
			public void onComplete(Object obj) {
				TeachingListData data = (TeachingListData) obj;
				
				//获取下一次请求需要的参数
				sViewState 		 = data.getViewState();
				sXn		  		 = data.getXn();
				sXq		  		 = data.getXq();
				sEventTarget 	 = data.getEventTarget();
				sEventArgument   = data.getEventArgument();
				classes			 = data.getClassList();
				sBj				 = data.getBj();
//				currentIndex	 = data.getSelectedClass();
				
				classesName = new ArrayList<String>();
				requetStrings = new ArrayList<String>();
				
				Iterator<String> iterator = classes.iterator();
				while(iterator.hasNext()){
					String s = iterator.next();
					String reString[] = s.split("\\|");		//对于“|”和“.”这样的转意字符需要这样处理来分隔
					classesName.add(reString[0].trim());
					requetStrings.add(reString[1].trim());
				}
				sKcmc			 = requetStrings.get(currentIndex);
				
				hasParam = true;
				
				LoadingDialog.dismiss();
				
				//判断是否请求的当前返回的课程数据
				if (classes.get(data.getSelectedClass()).contains(courseName)){
					/**
					 * 保存数据并且刷新界面
					 */
					mTeachList = data.getTeachList();
					saveStuNameList(courseName);
					
				}else {
					/**
					 * 从网络加载数据
					 */
					loadDataNextFromWeb();
				}
			}
		});
	}
	
	
	private void initSpinner(){
		//初始化下拉框
		ArrayAdapter spinnerAdapter = new ArrayAdapter<String>(EduTeaNameList.this, R.layout.spinner_style, classesName);
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(spinnerAdapter);
		spinner.setSelection(currentIndex);
	}
	
	/**
	 * 刷新界面
	 */
	private void refreshFrame(){
		if (null != mTeachList)
			title.setText("该班共：" + mTeachList.size() + "人");
		else {
			title.setText("学生名单查询");
		}
		
		adapter = new EduTeaNameListAdapter(EduTeaNameList.this, mTeachList);
		nameListView.setAdapter(adapter);
	}
	
	/**
	 * 将数据保存在本地
	 */
	private void saveDataLocal(String courseName){
		saveCourseNameList();
		saveStuNameList(courseName);
	}
	
	/**
	 * 保存科目列表
	 */
	private void saveCourseNameList(){
		dbAdapter.openDatabase();
		
		//判断是否可以插入
		if (!dbAdapter.isCourseListEnable()){
//			Log.e("信息", "不可以插入科目列表");
			return;
		}
		
		//保存课表
		Iterator<String> iterator = classesName.iterator();
		long index = dbAdapter.getNextCourseIndex();
		
		while (iterator.hasNext()){
			index = dbAdapter.saveCourses(index, iterator.next());
			
			index++;
		}
		
		//向数据库中插入一个终止符，表示科目已经全部插入，后面不用再修改科目列表信息
		dbAdapter.saveCourses(index, "0");
		
//		dbAdapter.printCourse();
		
		dbAdapter.closeDatabase();
	}
	
	/**
	 * 保存学生名单列表
	 */
	private void saveStuNameList(String courseName){
		dbAdapter.openDatabase();
		//首先获取可以插入的id号
		long id = dbAdapter.getNextIndex();
		//接着删除该班中的名单数据
		dbAdapter.deleteOneCourseStuList(courseName);
		
		//保存名单
		String course = classesName.get(currentIndex);
		
		Iterator<TeachingBean> iterator2 = mTeachList.iterator();
		while (iterator2.hasNext()){
			TeachingBean bean = iterator2.next();
			dbAdapter.addOneStudent(id, bean.number, bean.name, bean.professionName
					, bean.clsName, bean.grade, bean.coursecredit, bean.rebulid, course, bean.remark);
			
			id++;
		}
		
//		dbAdapter.printTable();
		
		dbAdapter.closeDatabase();
	}
	
	
	/**
	 * 根据课程名查询本地数据库中的学生信息
	 * @param courseName
	 */
	private void queryLocalData(String courseName){
		dbAdapter.openDatabase();
		mTeachList = dbAdapter.getOneCourseStudents(courseName);
		dbAdapter.closeDatabase();
		refreshFrame();
		
		if (null == mTeachList){
			Toast.makeText(EduTeaNameList.this, "该科目没有本地数据，请同步网络数据！", Toast.LENGTH_LONG).show();
		}
	}
	
	/**
	 * 同步网络数据时显示的提示对话框
	 */
	private void showRefreshDialog(){
		Builder builder = new Builder(this);
		builder.setTitle("提示").setMessage(R.string.refresh_hint)
		.setPositiveButton("同步", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (!application.isLogin()){
					Toast.makeText(EduTeaNameList.this, R.string.login_hint, Toast.LENGTH_LONG).show();
					return;
				}
				
				//同步网络数据则将数据库中的数据全部删除
				dbAdapter.openDatabase();
				//首先删除当前科目在数据库中的所有学生信息
				dbAdapter.deleteOneCourseStuList(classesName.get(currentIndex));
				dbAdapter.closeDatabase();
				
				//获取请求参数，然后开始请求数据
				if (!hasParam){
					getParamenter(classesName.get(currentIndex));
					
				}else {
					//已经有本地请求参数则直接加载课表信息
					sKcmc  = requetStrings.get(currentIndex);
					loadDataNextFromWeb();
				}
			}
		}).setNegativeButton("不同步", null).create().show();
	}

	
	@Override
	protected void onDestroy() {
		dbAdapter.closeDatabase();
		super.onDestroy();
	}
}
